<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{margin: 0;padding: 0;}
        .box{
            width: 400px;
            height: 500px;
            background: yellow;
            margin: 0 auto;
            margin-top: 10px;
            position: relative;
        }
        .bot{
            width: 100%;
            height: 100px;
            background: skyblue;
            position: absolute;
            bottom: 0;
        }
        .box2{
            width: 300px;
            height: 50px;
            background: #c0c0c0;
            position: absolute;
            top: 25px;
            left: 50px;
        }
        .inner{
            width: 50px;
            height: 50px;
            background: yellowgreen;
            position: absolute;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="bot">
            <div class="box2">
                <div class="inner"></div>
            </div>
        </div>
    </div>

    <script>
        var oInner=document.querySelector(".inner");
        var oBox2=document.querySelector(".box2");

        function offset(o) {
            var obj = { left: o.offsetLeft, top: o.offsetTop };
                                    //如果没有定位,就obj.offsetParent
            while (o.offsetParent) { //是否还有带定位的父元素怒
                o = o.offsetParent //你把父元素赋给自己,
                obj.left += o.offsetLeft; //累计相加 到 父元素距离,直到body
                obj.top += o.offsetTop;
            }
            return obj;
        }


        oInner.onmousedown=function(evt){
            var e=evt||window.event;
            var disX=e.pageX-offset(oInner).left;
            var left=offset(oBox2).left;


            document.onmousemove=function(evt){
                var e=evt||window.event;
                if(offset(oInner).left<left){
                    return;
                }else if(offset(oInner).left>(left+oBox2.offsetWidth-oInner.offsetWidth)){
                    return;
                }
                oInner.style.left=e.pageX-disX-left+"px";
            }


            document.onmouseup=function(){
                var iLeft=oInner.offsetLeft;
                document.onmouseup=document.onmousemove=null;
                if(iLeft<left||iLeft<(left+oBox2.offsetWidth)){
                oInner.style.left=0+"px";
                }
            }
        }

    </script>
</body>
</html>